package com.sec.android.app.myfiles.module.download.providerapps;

import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import com.sec.android.app.myfiles.info.MediaFile;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.AbsProviderImp;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.download.DownloadFileRecord.DownloadType;
import com.sec.android.app.myfiles.util.SemFwWrapper;

import java.io.UnsupportedEncodingException;

public class SimpleShareProviderImp extends AbsSupportAppProviderImp {
    private static final String SIMPLE_SHARE_AUTHORITY = "com.samsung.android.coreapps.rshare";
    private static final String LINK_SHARING_AUTHORITY = "com.samsung.android.app.simplesharing";
    private static final String LINK_SHARING_PACKAGE_NAME = "com.samsung.android.app.simplesharing";
    private static final int LINK_SHARING_ONE_APK_VERSION = 330000000;
    
    private static final String MEDIA_BOX = "media_box";
    private static final String SIMPLE_SHARE_APP = "app";
    private static final String FILEID = "_id";
    private static final String PATH = "local_file";
    private static final String SOURCE = "remote_uri";
    private static final String MIME_TYPE = "content_type";
    private static final String STATUS = "content_status";
    private static final String SIZE = "file_size";
    private static final String RECIPIENT_ID = "recipient_ids";
    private static final String ADDRESS = "address";
    private static final String[] SIMPLE_SHARE_PROJECTION = new String[]{
            FILEID, PATH, SOURCE, MIME_TYPE, STATUS, SIZE};

    private static Uri sSimpleShareUri = null;
    private static Uri sSimpleShareAddressUri = null;
    private int mFileIdIndex;
    private int mPathIndex;
    private int mSizeIndex;
    private int mMimeTypeIndex;
    private int mSourceIndex;
    private int mStatusIndex;

    public SimpleShareProviderImp(Context context, AbsProviderImp provider, SQLiteDatabase db) {
        super(context, provider, db);
        init(context);
    }

    public static Uri getSimpleShareUri() {
        return sSimpleShareUri;
    }

    private void init(Context context) {
        String simpleShareBase = "content://" + getAuthority(context);
        if (sSimpleShareUri == null) {
            sSimpleShareUri = Uri.parse(simpleShareBase + "/view_contents");
        }
        if (sSimpleShareAddressUri == null) {
            sSimpleShareAddressUri = Uri.parse(simpleShareBase + "/address");
        }
    }

    private String getAuthority(Context context) {
        return isSupportLinkSharing(context) ? LINK_SHARING_AUTHORITY : SIMPLE_SHARE_AUTHORITY;
    }

    private boolean isSupportLinkSharing(Context context) {
        boolean bRet = false;
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(LINK_SHARING_PACKAGE_NAME, 0);
            if (packageInfo.versionCode > LINK_SHARING_ONE_APK_VERSION) {
                bRet = true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("SimpleShareProviderImp", e.getMessage());
        }
        return bRet;
    }

    private String getQuery(int nMaxID) {
        StringBuilder query = new StringBuilder();
        query.append(FILEID);
        query.append(" > ");
        query.append(nMaxID);
        query.append(" and ");
        query.append(MEDIA_BOX);
        query.append(" == 1 and ");
        query.append(SIMPLE_SHARE_APP);
        query.append(" == 'remoteshare' ");

        return query.toString();
    }

    @Override
    protected Cursor getCursor() {
        int nMaxID = getProviderMaxIdEntry();

        //TODO Permission
        try {
            return mContentResolver.query(sSimpleShareUri, SIMPLE_SHARE_PROJECTION, getQuery(nMaxID), null, null);
        } catch (SecurityException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected ContentValues getContentValues(Cursor cursor) {
        ContentValues ret = null;

        int simpleShareId = cursor.getInt(mFileIdIndex);
        String _data = cursor.getString(mPathIndex);
        try {
            if (_data != null) {
                ret = new ContentValues();

                String fullPath = getConvertedPath(java.net.URLDecoder.decode(_data, "UTF-8"));

                String path = FileRecord.getPath(fullPath);
                String name = FileRecord.getName(fullPath);
                String extension = FileRecord.getExt(fullPath);
                int fileType = MediaFile.getFileType(fullPath);
                int size = cursor.getInt(mSizeIndex);
                String mimeType = cursor.getString(mMimeTypeIndex);
                String source = cursor.getString(mSourceIndex);
                int status = cursor.getInt(mStatusIndex);

                ret.put(COL_DownloadId, simpleShareId);
                ret.put(COL_Name, name);
                ret.put(COL_FileType, fileType);
                ret.put(COL_Size, size);
                ret.put(COL_Date, (SemFwWrapper.file(fullPath).lastModified()));
                ret.put(COL_Path, path);
                ret.put(COL_Ext, extension);
                ret.put(COL_MimeType, mimeType);
                ret.put(COL_Source, source);
                ret.put(COL_Description, getContactNumber(simpleShareId));
                ret.put(COL_Status, status);
                ret.put(COL_DownloadBy, DownloadType.DOWNLOAD_BY_SIMPLESHARE.ordinal());
            }
        } catch (UnsupportedEncodingException e) {
            Log.e(this, "UnsupportedEncodingException:" + e.toString());
            ret = null;
        }

        return ret;
    }

    private String getContactNumber(long id) {
        String contactNumber = null;
        String recipient_id = getRecipientIdFromSimpleShareMedia(id);

        if (recipient_id != null) {
            try (Cursor c = mContentResolver.query(sSimpleShareAddressUri, new String[]{
                    ADDRESS}, FILEID + " =" + recipient_id, null, null)) {

                if (c != null && c.moveToNext()) {
                    contactNumber = c.getString(0);
                }
            }
        }

        return contactNumber;
    }

    private String getRecipientIdFromSimpleShareMedia(long id) {
        String recipient_id = null;
        try (Cursor c = mContentResolver.query(sSimpleShareUri, new String[]{
                RECIPIENT_ID}, FILEID + " = " + id, null, null)) {

            if (c != null && c.moveToNext()) {
                recipient_id = c.getString(0);
            }
        }

        if (recipient_id != null) {
            int recIdx = recipient_id.indexOf(';');
            if (recIdx > 0) {
                recipient_id = recipient_id.substring(0, recIdx);
            }
        }

        return recipient_id;
    }

    private String getConvertedPath(String fullpath) {
        String path = fullpath;

        if (path.startsWith("file:")) {
            path = path.replace("file:", "");
        }

        return path;
    }

    @Override
    protected void setColumnIndex(Cursor cursor) {
        mFileIdIndex = cursor.getColumnIndex(FILEID);
        mPathIndex = cursor.getColumnIndex(PATH);
        mSizeIndex = cursor.getColumnIndex(SIZE);
        mMimeTypeIndex = cursor.getColumnIndex(MIME_TYPE);
        mSourceIndex = cursor.getColumnIndex(SOURCE);
        mStatusIndex = cursor.getColumnIndex(STATUS);
    }

    @Override
    protected boolean needClearUnnecessaryData() {
        return true;
    }

    @Override
    protected DownloadType getDownloadType() {
        return DownloadType.DOWNLOAD_BY_SIMPLESHARE;
    }
}
